<template>
  <div class="global-box goods">
    <div class="title">
      <h1>{{ title }}</h1>
      <a-button type="primary" @click="add('add')">添加商品</a-button>
    </div>
    <a-card :body-style="{ padding: '24px' }" :bordered="false">
      <div class="form-wrapper">
        <a-form layout="inline">
          <a-row :gutter="30">
            <a-col :md="6" :sm="24">
              <a-form-item label="课程目录">
                <a-cascader
                  :field-names="{ label: 'value', value: 'id', children: 'children' }"
                  :options="directoryOptions"
                  :load-data="loadData"
                  placeholder="请选择课程目录"
                  change-on-select
                  @change="getType"
                  v-model="queryParam.directory"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="课程类型">
                <a-select v-model="queryParam.type" placeholder="请选择课程类型" default-value="0">
                  <a-select-option
                    :key="item.classTypeId"
                    :value="item.classTypeId"
                    v-for="item in typeList"
                  >
                    {{ item.classTypeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="仓库状态">
                <a-select
                  v-model="queryParam.status"
                  placeholder="请选择仓库状态"
                  default-value="0"
                >
                  <a-select-option :value="item.value" :key="item.value" v-for="item in statusList">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商品名称">
                <a-input v-model="queryParam.name" placeholder="请输入商品名称" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商品ID">
                <a-input v-model="queryParam.id" placeholder=" 请输入商品ID" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="是否面授">
                <a-select v-model="queryParam.face" placeholder="请选择是否面授">
                  <a-select-option :value="item.value" :key="item.value" v-for="item in orList">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="是否高端班">
                <a-select v-model="queryParam.high" placeholder="请选择是否高端班">
                  <a-select-option :value="item.value" :key="item.value" v-for="item in orList">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons" style="float: right">
                <a-button type="primary" @click="search">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-wrapper">
        <a-table
          :row-selection="rowSelection"
          :columns="columns"
          :data-source="dataTable"
          :pagination="pagination"
          :rowKey="record => record.packageId"
        >
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleCopy(record)">复制</a>
              <a-divider type="vertical" />
              <a @click="APP(record)">APP内容管理</a>
              <a-divider type="vertical" />
              <a @click="changeRecord(record)">变更记录</a>
              <a-divider type="vertical" />
              <a @click="associated(record)">关联协议</a>
            </template>
          </span>
        </a-table>
        <div class="table-foot" style="margin-top: -47px">
          <a-button type="link" @click="showGoodsVisible">批量设置仓库状态</a-button>
          <a-button type="link" @click="showGoodsTime">批量设置上架时间</a-button>
        </div>
      </div>
      <!-- 仓库状态 -->
      <a-modal
        :title="goodsTitle"
        :visible="goodsVisible"
        @ok="goodsHandleOk"
        @cancel="goodsHandleCancel"
        okText="提交"
        cancelText="取消"
        width="20%"
      >
        <a-form-model
          class="ruleForm"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="仓库状态" prop="warehouseStatus">
            <a-radio-group v-model="form.warehouseStatus">
              <a-row v-for="item in warehouseStatusList" :key="item.value">
                <a-radio :value="item.value">
                  {{ item.label }}
                  <a-tooltip>
                    <template slot="title">{{ item.tip }}</template>
                    ①
                  </a-tooltip>
                </a-radio>
              </a-row>
            </a-radio-group>
          </a-form-model-item>
          <p class="form-status-tip">仓库状态修改影响商品在学员端的显示，请谨慎操作！</p>
        </a-form-model>
      </a-modal>
      <!-- 设置上架时间 -->
      <a-modal
        :title="timeTitle"
        :visible="timeVisible"
        @ok="timeHandleOk"
        @cancel="timeHandleCancel"
        okText="提交"
        cancelText="取消"
        width="20%"
      >
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="自动上架时间" prop="time">
            <a-date-picker
              show-time
              :disabled-date="disabledDate"
              format="YYYY-MM-DD HH:mm:ss"
              v-model="form.time"
              placeholder="请选择上架时间"
            />
          </a-form-model-item>
          <p class="form-status-tip">自动上架时间设置成功后商品会在指定时间自动上架。</p>
        </a-form-model>
      </a-modal>
      <!-- 变更记录 -->
      <a-modal
        title="变更记录"
        :visible="changeRecordVisible"
        @cancel="changeRecordVisible = false"
        width="50%"
        :footer="null"
      >
        <a-table
          :columns="changeRecordColumns"
          :data-source="changeRecordData"
          :pagination="changePagination"
          :rowKey="(record, index) => index"
        >
          <span slot="content" slot-scope="text, record">
            <template>
              <p>
                由 <a>{{ record.beforeChangeContent }}</a>
                变更为
                <a>{{ record.afterChangeContent }}</a>
              </p>
            </template>
          </span>
        </a-table>
      </a-modal>
    </a-card>
  </div>
</template>
<script>
import moment from 'moment'
import { directory, type, list, records, warehouseStatus, setTime } from '@/api/product/goods'
const columns = [
  {
    title: '商品ID',
    dataIndex: 'packageId',
    align: 'center'
  },
  {
    title: '商品名称',
    dataIndex: 'packageName',
    align: 'center'
  },
  {
    title: '课程类型',
    dataIndex: 'packageTypeName',
    align: 'center'
  },
  {
    title: '商品属性',
    dataIndex: 'packageAttribute',
    align: 'center'
  },
  {
    title: '商品价格',
    dataIndex: 'price',
    align: 'center'
  },
  {
    title: '关联协议名称',
    dataIndex: 'agreementName',
    align: 'center'
  },
  {
    title: '是否高端班',
    dataIndex: 'isHighEnd',
    align: 'center'
  },
  {
    title: '排序',
    dataIndex: 'sort',
    align: 'center'
  },
  {
    title: '仓库状态',
    dataIndex: 'warehouseStatus',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]
const changeRecordColumns = [
  {
    title: '变更字段',
    dataIndex: 'changeField',
    align: 'center'
  },
  {
    title: '变更内容',
    dataIndex: 'beforeChangeContent',
    width: '300px',
    scopedSlots: { customRender: 'content' },
    align: 'center'
  },
  {
    title: '变更人',
    dataIndex: 'userGroupName',
    align: 'center'
  },
  {
    title: '变更时间',
    dataIndex: 'createTime',
    align: 'center'
  }
]
export default {
  data () {
    return {
      moment,
      title: '商品管理',
      queryParam: {
        directory: [],
        type: undefined,
        status: undefined,
        name: '',
        id: '',
        face: undefined,
        high: undefined
      },
      columns,
      dataTable: [],
      changeRecordColumns,
      changeRecordData: [],
      selectedRowKeys: [],
      selectedRows: [],
      pagination: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => {
          this.pagination.defaultCurrent = 1
          this.pagination.defaultPageSize = pageSize
          this.getData()
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.pagination.defaultCurrent = current
          this.pagination.defaultPageSize = size
          this.getData()
        }
      },
      changePagination: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => {
          this.changePagination.defaultCurrent = 1
          this.changePagination.defaultPageSize = pageSize
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.changePagination.defaultCurrent = current
          this.changePagination.defaultPageSize = size
        }
      },
      typeList: [],
      directoryOptions: [],
      goodsVisible: false,
      changeRecordVisible: false,
      form: {
        warehouseStatus: 1,
        time: ''
      },
      rules: {
        warehouseStatus: [
          { required: true, message: '请选择仓库状态', trigger: 'change' }
        ],
        time: [
          { required: true, message: '请设置上架时间', trigger: 'change' }
        ]
      },
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
      courseData: {
        visible: false,
        row: ''
      },
      goodsTitle: '',
      warehouseStatusList: [
        {
          label: '上架',
          value: 1,
          tip: '上架状态：学员端与业务后台均显示'
        },
        {
          label: '下架',
          value: 0,
          tip: '下架状态：学员端不显示，业务后台可选择该课程'
        }
      ],
      timeTitle: '',
      timeVisible: false,
      statusList: [{
        label: '上架',
        value: 1
      },
      {
        label: '下架',
        value: 0
      }],
      orList: [{
        label: '是',
        value: 1
      },
      {
        label: '否',
        value: 0
      }]
    }
  },
  computed: {
    rowSelection () {
      const that = this
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          that.selectedRowKeys = selectedRowKeys
        },
        onSelectAll: (isSelected, selectedRows, changedRows) => {
          if (isSelected) {
            that.selectedRows = [...that.selectedRows, ...selectedRows]
          } else {
            const removedIds = changedRows.map(i => i.packageId)
            that.selectedRows = that.selectedRows.filter(i => !removedIds.includes(i.packageId))
          }
        },
        onSelect: (record, isSelected) => {
          if (isSelected) {
            that.selectedRows.push(record)
          } else {
            that.selectedRows = that.selectedRows.filter(i => i.packageId !== record.packageId)
          }
        },
        getCheckboxProps: (record) => ({
          props: {
            checked: that.selectedRowKeys.indexOf(record.packageId) > -1
          }
        })
      }
    }
  },
  mounted () {
    this.getDirectory()
    this.getData()
  },
  methods: {
    // 获取列表数据
    getData () {
      const data = {
        currentPage: this.pagination.defaultCurrent,
        pageSize: this.pagination.defaultPageSize
      }
      if (this.queryParam.type !== '') {
        data.packageTypeId = this.queryParam.type
      }
      if (this.queryParam.status !== '') {
        data.warehouseStatus = this.queryParam.status
      }
      if (this.queryParam.name !== '') {
        data.packageName = this.queryParam.name
      }
      if (this.queryParam.id !== '') {
        data.packageId = this.queryParam.id
      }
      if (this.queryParam.face !== '') {
        data.isFaceTeaching = this.queryParam.face
      }
      if (this.queryParam.high !== '') {
        data.isHighEnd = this.queryParam.high
      }
      if (this.queryParam.directory[0]) {
        data.directoryId = this.queryParam.directory[0]
      }
      if (this.queryParam.directory[1]) {
        data.examId = this.queryParam.directory[1]
      }
      if (this.queryParam.directory[2]) {
        data.subjectId = this.queryParam.directory[2]
      }
      if (this.queryParam.directory[3]) {
        data.fourExamId = this.queryParam.directory[3]
      }
      if (this.queryParam.directory[4]) {
        data.fiveExamId = this.queryParam.directory[4]
      }
      if (this.queryParam.directory[5]) {
        data.sixExamId = this.queryParam.directory[5]
      }
      list(data).then(res => {
        if (res.code === '1') {
          this.pagination.total = res.data.totalSize
          this.dataTable = res.data.rows
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 批量设置仓库状态
    showGoodsVisible () {
      if (this.selectedRowKeys.length > 0) {
        this.goodsTitle = `批量设置课程状态（已选${this.selectedRowKeys.length}个）`
        this.goodsVisible = true
      } else {
        this.$message.error('请选择课程！')
      }
    },
    // 批量设置仓库状态确定
    goodsHandleOk () {
      const data = {
        isActive: this.form.warehouseStatus,
        packageIds: this.selectedRowKeys
      }
      warehouseStatus(data).then(res => {
        if (res.code === '1') {
          this.$message.success(res.msg)
          this.goodsVisible = false
          this.getData()
          this.selectedRowKeys = []
          this.selectedRows = []
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 批量设置仓库状态取消
    goodsHandleCancel () {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.form.warehouseStatus = 1
      this.goodsVisible = false
    },
    // 批量设置上架时间
    showGoodsTime () {
      if (this.selectedRowKeys.length > 0) {
        this.timeTitle = `批量设置上架时间（已选${this.selectedRowKeys.length}个）`
        this.timeVisible = true
      } else {
        this.$message.error('请选择课程！')
      }
    },
    // 禁止当前日期之前
    disabledDate (current) {
      return current && current < moment().endOf('day')
    },
    // 批量设置上架时间确定
    timeHandleOk () {
      const data = {
        openTime: moment(this.form.time).format('YYYY-MM-DD HH:mm:ss'),
        packageIds: this.selectedRowKeys
      }
      setTime(data).then(res => {
        if (res.code === '1') {
          this.$message.success(res.msg)
          this.timeVisible = false
          this.form.time = null
          this.getData()
          this.selectedRowKeys = []
          this.selectedRows = []
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 批量设置上架时间取消
    timeHandleCancel () {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.form.time = null
      this.timeVisible = false
    },
    // 查询
    search () {
      this.getData()
    },
    // 重置
    reset () {
      this.queryParam = {
        directory: [],
        type: undefined,
        status: undefined,
        name: '',
        id: '',
        face: '',
        high: ''
      }
      this.getData()
    },
    // 表格编辑
    handleEdit (record) {
      this.$router.push({
        name: 'productGoodsCommon',
        params: {
          packageId: record.packageId,
          edit: true
        }
      })
    },
    // 添加商品
    add () {
      this.$router.push({
        name: 'productGoodsCommon'
      })
    },
    // 表格复制
    handleCopy (record) {
      this.$router.push({
        name: 'productGoodsCommon',
        params: {
          packageId: record.packageId,
          edit: false
        }
      })
    },
    // APP内容管理
    APP (record) {
      this.$router.push({
        name: 'productGoodsApp',
        params: {
          packageId: record.packageId
        }
      })
    },
    // 变更记录
    changeRecord (row) {
      const data = {
        currentPage: this.changePagination.defaultCurrent,
        packageId: row.packageId,
        pageSize: this.changePagination.defaultPageSize
      }
      records(data).then(res => {
        if (res.code === '1') {
          this.changeRecordVisible = true
          this.changePagination.total = res.data.totalSize
          this.changeRecordData = res.data.rows
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 关联协议
    associated (record) {
      console.log(record)
      this.$router.push({
        name: 'productGoodsAgree',
        params: {
          packageId: record.packageId
        }
      })
    },
    // 获取课程目录
    getDirectory () {
      const data = {
        type: 0,
        directoryLevel: 1
      }
      directory(data).then(res => {
        if (res.code === '1') {
          res.data.forEach(item => {
            item.isLeaf = false
          })
          this.directoryOptions = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 课程目录二级-六级
    loadData (selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const data = {
        type: 1,
        parentId: targetOption.id,
        directoryLevel: 2
      }
      targetOption.loading = true
      directory(data).then(res => {
        if (res.code === '1') {
          if (res.data.length > 0) {
            res.data.forEach(item => {
              item.isLeaf = false
            })
            targetOption.loading = false
            targetOption.children = [...res.data]
          } else {
            targetOption.loading = false
            this.$message.error('暂无更多数据')
          }
        } else {
          targetOption.loading = false
          this.$message.error(res.msg)
        }
        this.directoryOptions = [...this.directoryOptions]
      }).catch(err => {
        this.$message.error(err.msg)
        targetOption.loading = false
      })
    },
    // 获取课程类型
    getType () {
      if (this.queryParam.directory.length === 0) {
        this.typeList = []
        this.queryParam.type = undefined
      }
      if (!this.queryParam.directory[1]) {
        return false
      }
      if (this.oldExamId === this.queryParam.directory[1]) {
        return false
      }
      const data = {
        examId: this.queryParam.directory[1]
      }
      type(data).then(res => {
        if (res.code === '1') {
          this.typeList = res.data
          this.queryParam.type = undefined
          this.oldExamId = this.queryParam.directory[1]
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.form-status-tip {
  text-align: center;
  color: #999;
}
</style>
<style lang="less">
.goods {
  .form-wrapper .ant-form-inline .ant-form-item > .ant-form-item-label {
    width: 100px;
  }
}
.ruleForm {
  .ant-form-item-label {
    line-height: initial;
  }
  .ant-row {
    margin-bottom: 10px;
  }
}
</style>
